//
//  XYLocalPush.m
//  iFeller
//
//  Created by rimi on 15/12/21.
//  Copyright © 2015年 Wii. All rights reserved.
//

#import "XYLocalPush.h"

@implementation XYLocalPush
+ (void)registerLocalNotification:(NSDate *)pushDate
                         pushName:(NSString *)pushName
                         pushRepeat:(NSString *)pushRepeat
                    {
    UILocalNotification *localNotification = [[UILocalNotification alloc] init];
    
    localNotification.fireDate = pushDate;
    localNotification.timeZone = [NSTimeZone localTimeZone];
    //重复间隔
    localNotification.repeatInterval = [self choozeTheRepeat:pushRepeat];
    //通知内容 事件名称
    localNotification.alertBody = pushName;
    localNotification.soundName = UILocalNotificationDefaultSoundName;
    //动态key值
    NSString *string = [NSString stringWithFormat:@"%@", pushDate];
    NSDictionary *userDict = @{string:pushName, @"key":string};
    NSLog(@"%@", userDict);
    localNotification.userInfo = userDict;
    
    //注册通知授权
    if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
        UIUserNotificationType type =  UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type
                                                                                 categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    }
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
                        
//                        NSArray *localNotifications = [UIApplication sharedApplication].scheduledLocalNotifications;
//                        NSLog(@"%@", localNotifications);
}

+ (void)cancelLocalNotification:(NSString *)pushDate {
    NSArray *localNotifications = [UIApplication sharedApplication].scheduledLocalNotifications;
    for (UILocalNotification *notification in localNotifications) {
        NSDictionary *userInfo = notification.userInfo;
        if (userInfo) {
            NSString *info = userInfo[pushDate];
            if (info != nil) {
                [[UIApplication sharedApplication] cancelLocalNotification:notification];
                break;
            }
        }
    }
}

+ (NSCalendarUnit)choozeTheRepeat:(NSString *)repeat {
    if ([repeat isEqualToString:@"每小时"]) {
        return NSCalendarUnitHour;
    } else if ([repeat isEqualToString:@"每天"]) {
        return NSCalendarUnitDay;
    } else if ([repeat isEqualToString:@"每周"]) {
        return NSCalendarUnitWeekday;
    } else if ([repeat isEqualToString:@"每月"]) {
        return NSCalendarUnitMonth;
    } else if ([repeat isEqualToString:@"每年"]) {
        return NSCalendarUnitYear;
    }
    return 0;
}
@end
